package com.luo.ai.assistant.conv.dao;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.luo.ai.assistant.conv.model.Chat;
import com.luo.ai.assistant.conv.model.ChatQuery;
import com.luo.ai.assistant.file.dao.MyBaseMapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 聊天记录DAO
 *
 * @author luohq
 * @date 2025-02-05
 */
@Mapper
public interface ChatMapper extends MyBaseMapper<Chat> {

    /**
     * Delete chats by conversation ids.
     *
     * @param convIds conversation ids
     * @return number of rows affected
     */
    default Integer deleteByConvIds(Collection<Long> convIds) {
        return this.delete(Wrappers.<Chat>lambdaUpdate()
                .in(Chat::getConversationId, convIds));
    }

    /**
     * Find chat history.
     *
     * @param chatQuery chat query
     * @return chat history
     */
    default List<Chat> findChatHistory(ChatQuery chatQuery) {
        return this.selectList(Wrappers.<Chat>lambdaQuery()
                .eq(Chat::getConversationId, chatQuery.getConvId())
                .gt(Objects.nonNull(chatQuery.getFromChatId()), Chat::getId, chatQuery.getFromChatId())
                .orderBy(true, false, Chat::getCreateTime)
                .last(Objects.nonNull(chatQuery.getLimit()), "LIMIT " + chatQuery.getLimit()));
    }
}